import { MessageBox, Loading, Message } from 'element-ui';
import request from '../utils/request';
import Store from '../store/index';

request.interceptors.request.use(
  config => {
    if (Store.state.token) {
      Object.assign(config.headers, { 'AuthToken': Store.state.token })
    }
    return config;
  },
  error => {
    return Promise.reject();
  }
);
export const fetchData = query => {
  return request({
    url: './table.json',
    method: 'get',
    params: query
  });
};

export const login = query => {
  return request({
    url: './api/userlogin',
    method: 'get',
    params: query
  });
};

export const FileUpload = option => {
  return request(Object.assign({
    url: './api/File',
    method: 'post',
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 30000
  }, option));
};

import Router from '../router/index'
let _temp_user_unauthorized_confirm = false
/**
 * 标准处理请求信息
 * @param {*} request 请求回调 
 * @param {*} page 页面vue实例
 * @param {*} dowith 处理方法对象{success}
 */
export const StandardDoWith = (request, page, dowith) => {
  let loadingInstance = null;
  if (dowith && dowith.loading) {
    if (typeof dowith.loading == "string") dowith.loading = { text: dowith.loading }
    loadingInstance = Loading.service(Object.assign({
      lock: true,
      text: '网络请求中',
      spinner: 'el-icon-loading',
    }, dowith.loading));

  }
  request.then(res => {
    if (dowith && dowith.loading) {
      loadingInstance.close();
    }
    if (res) {
      if (res.code == 0) {
        if (dowith.success) dowith.success(res.detail)
      } else if (res.code == 902) {
        if (!_temp_user_unauthorized_confirm) {
          _temp_user_unauthorized_confirm = true
          MessageBox.confirm('用户信息已过期，请先进行登录操作？', '提示', {
            type: 'warning'
          })
            .then(() => {
              // page.$router.push({ name: 'login' })
              _temp_user_unauthorized_confirm = false
              Router.push({ name: 'login' })
            }).catch(() => {
              _temp_user_unauthorized_confirm = false
            })
        }

        if (dowith.fail) dowith.fail()
      } else {

        Message.error(res.message || `操作失败`);
        if (dowith.fail) dowith.fail()
      }
    } else {
      Message.error(`非标准格式，处理失败`);
      if (dowith.fail) dowith.fail()
    }
    if (dowith.complete) dowith.complete()

  }).catch(err => {
    if (dowith && dowith.loading) {
      loadingInstance.close();
    }
    Message.error(`请求失败`);
    if (dowith.fail) dowith.fail()
    if (dowith.complete) dowith.complete()

  });
};

export const getCourier = query => {
  return request({
    url: './api/Courier',
    method: 'get',
    params: query,
    headers: { 'AuthToken': GetToken() }
  });
};


const RestfulAutoInterface = (url, methods) => {
  if (!methods) methods = ["Get", "Post"]
  let REST = {}
  methods.map(method => {
    switch (method) {
      default: {
        REST[method] = params => {
          return request({
            url,
            method,
            params,
          });
        }
        break
      }
      case "Patch":
      case "Put":
      case "Post": {
        REST[method] = data => {
          let params = {}
          if (data && data.params) {
            params = data.params
            delete data.params
          }
          return request({
            url,
            method,
            params,
            data,
          });
        }
        break
      }
    }
  })
  return REST
}
/**
 * 统一xlsx文件下载处理
 * @param {*} request 
 * @param {*} filename 
 */
const StandardDownFile = (request, filename) => {
  let loadingInstance = Loading.service({
    lock: true,
    text: '下载请求处理中',
    spinner: 'el-icon-loading',
  });
  request.then(response => {
    loadingInstance.close()
    if (response) {
      let url = window.URL.createObjectURL(new Blob([response]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', filename)
      document.body.appendChild(link)
      link.click()
      link.remove()
    } else {
      Message.error('下载请求数据异常');
    }
  }).catch(() => {
    loadingInstance.close()
    Message.error('下载请求失败');
  })
}
const Currency = RestfulAutoInterface('./api/Currency', ["Get", "Post", "Put", "Delete"])
const Agent = RestfulAutoInterface('./api/Agent', ["Get", "Post", "Put", "Delete"])
const Nation = RestfulAutoInterface('./api/Nation', ["Get", "Post", "Put", "Delete"])
const Repository = RestfulAutoInterface('./api/Repository', ["Get", "Post", "Put", "Delete"])
const Courier = RestfulAutoInterface('./api/Courier', ["Get", "Post", "Put", "Delete"])
const PackageIn = RestfulAutoInterface('./api/PackageIn')
const PackageClaim = RestfulAutoInterface('./api/Claim')
const RepositoryIn = RestfulAutoInterface('./api/RepositoryIn')
const CourierChannel = RestfulAutoInterface('./api/Channel', ["Get", "Post", "Put", "Delete"])
const PackageApplyOut = RestfulAutoInterface('./api/OrderApply')
const PackageDeliver = RestfulAutoInterface('./api/OrderApplyExpress', ["Get", "Post", "Put"])
const Package = RestfulAutoInterface('./api/Package')
const Sysuser = RestfulAutoInterface('./api/SysUser', ["Get", "Post", "Put", "Patch"])
const SysUserExtra = RestfulAutoInterface('./api/SysUserExtra', ["Put"])
const Appuser = RestfulAutoInterface('./api/AppUser', ["Get", "Put"])
const Income = RestfulAutoInterface('./api/Income')
const AgentFee = RestfulAutoInterface('./api/AgentFee')
const UserAccountCharge = RestfulAutoInterface('./api/Useraccountcharge', ["Get", "Post", "Patch"])
const RoleManage = RestfulAutoInterface('./api/Role', ["Get", "Post", "Put", "Delete"])
const PermissionManage = RestfulAutoInterface('./api/Rolemenufunction', ["Get", "Put"])
const FindAgentCourier = RestfulAutoInterface('./api/Courier2Agent')
const ExchangeRate = RestfulAutoInterface('./api/Currencychangerate', ["Get", "Post", "Put", "Delete"])
const PackageCheck = RestfulAutoInterface('./api/Packagecheck', ["Put"])
const PackageRefund = RestfulAutoInterface('./api/Packagerefund', ["Put"])
const PackageChange = RestfulAutoInterface('./api/PackageChange', ["Put"])
const OrderProfit = RestfulAutoInterface('./api/OrderProfit', ["Get"])
const PackageInPre = RestfulAutoInterface('./api/PackageInPre')
/**收支核算 */
const Profit = RestfulAutoInterface('./api/Profit')
/**运营成本 */
const RunFee = RestfulAutoInterface('./api/RunFee')

const ChannelPrice = RestfulAutoInterface('./api/Channelprice', ["Get", "Post"])
/**运营成本 */
const SystemSetting = RestfulAutoInterface('./api/Syssetting', ["Get", "Post", "Put", "Delete"])
const ChannelDescription = RestfulAutoInterface('./api/Channeldescription', ["Get", "Post"])
const RepositoryRegion = RestfulAutoInterface('./api/Repositoryregion', ["Get", "Post", "Delete", "Put"])
const RepositoryShelf = RestfulAutoInterface('./api/Repositoryshelf', ["Get", "Post", "Delete", "Put"])
const RepositoryLayer = RestfulAutoInterface('./api/Repositorylayer', ["Get", "Post", "Delete", "Put"])
const OrderApplyExpressStatus = RestfulAutoInterface('./api/OrderApplyExpressStatus', ["Get"])
const OrderApplyAccount = RestfulAutoInterface('./api/OrderApplyAccount', ["Get", "Post", "Put"])
const AgentFeeAccount = RestfulAutoInterface('./api/AgentFeeAccount', ["Get"])
const AppUserData = RestfulAutoInterface('./api/AppUserData', ["Get"])
const AgentUserData = RestfulAutoInterface('./api/AgentUserData', ["Get"])
const OrderError = RestfulAutoInterface('./api/OrderError', ["Get", "Post"])
const Appnew = RestfulAutoInterface('./api/Appnew', ["Get", "Post", "Delete", "Put"])
const Appnewcontent = RestfulAutoInterface('./api/Appnewcontent', ["Get"])
const HomePage = RestfulAutoInterface('./api/HomePage', ["Get"])
const Goodtypel = RestfulAutoInterface('./api/Goodtypel', ["Get"])
const Goodtypel1 = RestfulAutoInterface('./api/Goodtypel1', ["Get", "Post", "Delete", "Put"])
const Goodtypel2 = RestfulAutoInterface('./api/Goodtypel2', ["Get", "Post", "Delete", "Put"])
const UserChargeConsume = RestfulAutoInterface('./api/UserChargeConsume', ["Get", "Post"])
const UserLogin = RestfulAutoInterface('./api/UserLogin', ["Get", "Put"])
const Channeltype = RestfulAutoInterface('./api/Channeltype', ["Get", "Post", "Delete"])
const Userchargeqrcodeimage = RestfulAutoInterface('./api/Userchargeqrcodeimage', ["Get", "Post", "Put", "Delete"])

const AgentUserDataExport = params => {
  return request({ url: './api/AgentUserDataExport', method: "get", params, responseType: 'blob', });
}

const RepositoryInExport = params => {
  return request({ url: './api/RepositoryInExport', method: "get", params, responseType: 'blob', });
}
const OrderApplyExport = params => {
  return request({ url: './api/OrderApplyExport', method: "get", params, responseType: 'blob', });
}
const OrderApplyExpressExport = params => {
  return request({ url: './api/OrderApplyExpressExport', method: "get", params, responseType: 'blob', });
}
const PackageExport = params => {
  return request({ url: './api/PackageExport', method: "get", params, responseType: 'blob', });
}
const OrderProfitExport = params => {
  return request({ url: './api/OrderProfitExport', method: "get", params, responseType: 'blob', });
}
const IncomeExport = params => {
  return request({ url: './api/IncomeExport', method: "get", params, responseType: 'blob', });
}
const RunFeeExport = params => {
  return request({ url: './api/RunFeeExport', method: "get", params, responseType: 'blob', });
}
const OrderApplyAccountExport = params => {
  return request({ url: './api/OrderApplyAccountExport', method: "get", params, responseType: 'blob', });
}
const ProfitExport = params => {
  return request({ url: './api/ProfitExport', method: "get", params, responseType: 'blob', });
}
const UseraccountchargeExport = params => {
  return request({ url: './api/UseraccountchargeExport', method: "get", params, responseType: 'blob', });
}
const AppUserExport = params => {
  return request({ url: './api/AppUserExport', method: "get", params, responseType: 'blob', });
}
const AgentFeeExport = params => {
  return request({ url: './api/AgentFeeExport', method: "get", params, responseType: 'blob', });
}
const PackageInExport = params => {
  return request({ url: './api/PackageInExport', method: "get", params, responseType: 'blob', });
}
const ClaimExport = params => {
  return request({ url: './api/ClaimExport', method: "get", params, responseType: 'blob', });
}
const ShippmentExport = params => {
  return request({ url: './api/ShippmentExport', method: "get", params, responseType: 'blob', });
}
const TagExport = params => {
  return request({ url: './api/TagExport', method: "get", params, responseType: 'blob', });
}
const InvoiceExport = params => {
  return request({ url: './api/InvoiceExport', method: "get", params, responseType: 'blob', });
}
export default {
  StandardDoWith, StandardDownFile,
  Currency, Agent, Nation, Repository, Courier, PackageIn, RepositoryIn, CourierChannel, PackageApplyOut, PackageDeliver, Package, UserAccountCharge,
  AgentFee, PackageClaim, RoleManage, PermissionManage, FindAgentCourier, ExchangeRate, PackageCheck, PackageRefund, PackageChange, PackageInPre,
  FileUpload, Userchargeqrcodeimage,
  Sysuser, Appuser, Income,
  OrderProfit,
  Sysuser, Appuser, Income, Profit, RunFee, SystemSetting,
  ChannelPrice, ChannelDescription, RepositoryRegion, RepositoryShelf, RepositoryLayer,
  OrderApplyExpressStatus, OrderApplyAccount, AgentFeeAccount, AppUserData, AgentUserData, OrderError, Appnew, Appnewcontent,
  AgentUserDataExport,
  RepositoryInExport, OrderApplyExport, OrderApplyExpressExport, PackageExport, OrderProfitExport, IncomeExport, RunFeeExport, OrderApplyAccountExport, ProfitExport, AppUserExport, UseraccountchargeExport, AgentFeeExport, PackageInExport, ClaimExport,
  HomePage, Goodtypel, Goodtypel1, Goodtypel2, UserChargeConsume, UserLogin, Channeltype, SysUserExtra,
  ShippmentExport, TagExport, InvoiceExport
}
